<template>
  <div>
    <button @click="open">{{ miao }}</button>
  </div>
</template>
<script>
let timer_tanchuang
export default {
  name: 'YanZheng',
  props: {
    // 秒
    time: {
      type: Number,
      default: 60 * 5
    }
  },
  data() {
    return {
      miao: this.time,
      numer: this.getRandomNumber()
    }
  },
  mounted() {
    this.startBackwards()
  },
  beforeDestroy() {
    this.stopBackward()
  },
  methods: {
    getRandomNumber(min = 1, max = 99) {
      return Math.floor(Math.random() * (max - min + 1)) + min
    },
    startBackwards() {
      this.stopBackward()
      setInterval(() => {
        --this.miao
      }, 1000)
      timer_tanchuang = setTimeout(() => {
        this.open()
        this.stopBackward()
      }, this.time * 1000)
    },
    stopBackward() {
      if (timer_tanchuang) clearTimeout(timer_tanchuang)
    },
    open() {
      this.$emit('open')
      this.$prompt(`请输入数字 ${this.numer} `, '防作弊', {
        closeOnPressEscape: false,
        closeOnClickModal: false,
        confirmButtonText: '确定',
        showCancelButton: false,
        showClose: false,
        inputValidator: (value) => {
          // 点击按钮时，对文本框里面的值进行验证
          if (!value) {
            return '输入不能为空'
          } else if (value * 1 !== this.numer) {
            return '输入错误'
          }
        }
      }).then(({ value }) => {
        this.numer = this.getRandomNumber()
        this.miao = this.time
        this.startBackwards()
        if (value * 1 !== this.numer) {
          this.$emit('error')
        }
      })
    }
  }
}
</script>
